package com.denlaku.longan.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @author tianx
 */
public final class Lists {

    public static <T> List<T> empty() {
        return ofSize(0);
    }

    public static <T> List<T> ofSize(int size) {
        return new ArrayList<>(Math.max(size, 0));
    }

    @SafeVarargs
    public static <T> List<T> of(T ...values) {
        if (values == null) {
            return empty();
        }
        List<T> list = ofSize(values.length);
        Collections.addAll(list, values);
        return list;
    }

    public static <T> List<T> of(Collection<T> values) {
        if (values == null) {
            return empty();
        }
        List<T> list = ofSize(values.size());
        list.addAll(values);
        return list;
    }

    private static <T> boolean isEmpty(List<T> list) {
        return list == null || list.isEmpty();
    }

    public static <T> List<T> filter(List<T> list, Predicate<? super T> filter) {
        if (isEmpty(list)) {
            return empty();
        }
        return list.stream().filter(filter).collect(Collectors.toList());
    }

    public static <T, R> List<R> toList(List<T> list, Function<T, R> mapper) {
        if (isEmpty(list)) {
            return empty();
        }
        return list.stream().map(mapper).collect(Collectors.toList());
    }

    public static <T, K, V> Map<K, V> toMap(List<T> list, Function<? super T, ? extends K> keyMapper,
                                            Function<? super T, ? extends V> valueMapper) {
        if (isEmpty(list)) {
            return Maps.empty();
        }
        return list.stream().collect(Collectors.toMap(keyMapper, valueMapper));
    }

    private Lists() {
    }
}
